<template>
  <!-- 页头 -->
  <van-nav-bar title="详情页" class="nav-var-header" left-arrow fixed @click-left="() => {router.push({path:'/'})}"/>
  <div class="content">
    <van-image class="result-img" :src="arr[route.query.sku_id].banner"/>
    <div class="title font-38-px">
      <div class="font-b">{{ skuData.sku_name ? skuData.sku_name : arr[route.query.sku_id].title }}</div>
    </div>
    <div class="act-desc font-32-px">
      <div class="font-b desc-title"><span style="color: #F43127; font-weight: bolder">|</span>&nbsp&nbsp商品详情
      </div>
      <van-image style="margin: 10px auto" v-for="item in arr[route.query.sku_id].descImgArr" :src="item"/>
    </div>
    <van-action-bar class="action_bar">
      <van-action-bar-icon icon="wap-home-o" text="主页" :onclick="() => {router.push({path: '/home'})}"/>
      <van-action-bar-icon icon="orders-o" text="订单列表" :onclick="() => {router.push({path: '/order'})}"/>
      <van-action-bar-button type="danger" :disabled="disabledBtn"
                             :class="skuData.is_obtained === 1 ? 'obtained_btn' : ''"
                             :text="btnStatueText" @click="handleGetBtnChange"/>
    </van-action-bar>
    <van-overlay :show="isOverlay">
      <div class="wrapper" :style="bgStyle">
        <div>
          <div class="btn font-b">
            <van-button class="cancel-btn" type="default" round @click="isOverlay = false">取消</van-button>
            <van-button class="confirm-btn" color="linear-gradient(to bottom, #FD973C, #DF371A)" round
                        @click="handleBocObtainChange">确认
            </van-button>
          </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script setup>
import jiayouBanner from "@/assets/image/jiayou_banner.png"
import huarunbltBanner from "@/assets/image/huarunblt_banner.png"
import huarunoleBanner from "@/assets/image/huarunole_banner.png"
import yunnanbaiyaoBanner from "@/assets/image/yunnanbaiyao_banner.png"
import hemaBanner from "@/assets/image/4banner_bg5.png"
import haigeBanner from "@/assets/image/haige_banner.png"
import maoyanBanner from "@/assets/image/maoyan_banner.png"
import Banner_711 from "@/assets/image/711_banner.png"
import hagendasiBanner from "@/assets/image/hagendasi_banner.png"
import jiahuaBanner from "@/assets/image/jiahua_banner.png"
import hanbaoBanner from "@/assets/image/hanbao_banner.png"
import lengyinBanner from "@/assets/image/lengyin_banner.png"
import xuelanBanner from "@/assets/image/xuelan_banner.png"
import meituanBanner from "@/assets/image/meituan_banner.png"
import wxBanner from "@/assets/image/wx_banner.png"
import particulars2_711 from "@/assets/image/711/particulars2_711.png"
import hbw_particulars2 from "@/assets/image/hbw/hbw_particulars2.png"
import particulars2 from "@/assets/image/hgds/hgds_particulars2.png"
import particulars3 from "@/assets/image/hgds/hgds_particulars3.png"
import particulars4 from "@/assets/image/hgds/hgds_particulars4.png"
import hggj_particulars2 from "@/assets/image/hggj/hggj_particulars2.png"
import hggj_particulars3 from "@/assets/image/hggj/hggj_particulars3.png"
import hggj_particulars4 from "@/assets/image/hggj/hggj_particulars4.png"
import hmxs_particulars1 from "@/assets/image/hmxs/particulars1.png"
import hmxs_particulars2 from "@/assets/image/hmxs/hmxs_particulars2.png"
import hmxs_particulars3 from "@/assets/image/hmxs/hmxs_particulars3.png"
import hmxs_particulars4 from "@/assets/image/hmxs/hmxs_particulars4.png"
import hrblt_particulars2 from "@/assets/image/hr_blt/hrblt_particulars2.png"
import hrole_particulars2 from "@/assets/image/hr_ole/hrole_particulars2.png"
import jhbw_particulars2 from "@/assets/image/jhbw/jhbw_particulars2.png"
import jhbw_particulars3 from "@/assets/image/jhbw/jhbw_particulars3.png"
import jhbw_particulars4 from "@/assets/image/jhbw/jhbw_particulars4.png"
import jyhy_particulars1 from "@/assets/image/jy/jyhy_particulars1.png"
import jyhy_particulars2 from "@/assets/image/jy/jyhy_particulars2.png"
import lyhy_particulars2 from "@/assets/image/ly/lyhy_particulars2.png"
import lyhy_particulars1 from "@/assets/image/ly/lyhy_particulars1.png"
import mtwm_particulars2 from "@/assets/image/mt/mtwm_particulars2.png"
// import mtwm_particulars4 from "@/assets/image/mt/mtwm_particulars4.png"
import mydy_particulars2 from "@/assets/image/mydy/mydy_particulars2.png"
import mydy_particulars3 from "@/assets/image/mydy/mydy_particulars3.png"
import mydy_particulars4 from "@/assets/image/mydy/mydy_particulars4.png"
import wxlj_particulars2 from "@/assets/image/wx/wxlj_particulars2.png"
import xlnn_particulars2 from "@/assets/image/xl/xlnn_particulars2.png"
import ynby_particulars2 from "@/assets/image/yn/ynby_particulars2.png"
import orderTip10 from "@/assets/image/mydy/order_tip_mydy.png"
import orderTip9 from "@/assets/image/jhbw/order_tip_jhbw.png"
import orderTip8 from "@/assets/image/hmxs/order_tip_hmxs.png"
import orderTip7 from "@/assets/image/hggj/order_tip_hggj.png"
import orderTip6 from "@/assets/image/hgds/order_tip_hgds.png"
import orderTip5 from "@/assets/image/order_tip_mtwm1.png"
import orderTip1 from "@/assets/image/order_tip_1.png"
import {useRouter, useRoute} from 'vue-router'
import {onMounted, ref, computed} from "vue";
import {bocObtain, payGetPayParams, skuInfo, skuStock, paySuccess, checkObtain} from "@/api/index.js";
import {showFailToast, showToast} from "vant";

const router = useRouter()
const route = useRoute()
const isOverlay = ref(false);
const bgImage = ref(orderTip1);
const bgStyle = computed(() => ({
  backgroundImage: `url(${bgImage.value})`,
  // 其他样式
}))
const storeData = ref({})
const arr = {
  3052: {
    title: '加油行业立减券', banner: jiayouBanner, descImgArr: [jyhy_particulars1,jyhy_particulars2,]
  },
  3036: {
    title: '华润 Ole', banner: huarunoleBanner, descImgArr: [hrole_particulars2]
  },
  3037: {
    title: '华润 Blt', banner: huarunbltBanner, descImgArr: [hrblt_particulars2]
  },
  3038: {
    title: '云南白药', banner: yunnanbaiyaoBanner, descImgArr: [ynby_particulars2]
  },
  3034: {
    title: '盒马', banner: hemaBanner, descImgArr: [hmxs_particulars1,
      hmxs_particulars2,
      hmxs_particulars3,
      hmxs_particulars4]
  },
  3049: {
    title: '海格管家', banner: haigeBanner, descImgArr: [hmxs_particulars1,
      hggj_particulars2,
      hggj_particulars3,
      hggj_particulars4]
  },
  3045: {
    title: '猫眼电影券', banner: maoyanBanner, descImgArr: [hmxs_particulars1,
      mydy_particulars2,
      mydy_particulars3,
      mydy_particulars4]
  },
  3051: {
    title: '711', banner: Banner_711, descImgArr: [particulars2_711]
  },
  3047: {
    title: '哈根达斯', banner: hagendasiBanner, descImgArr: [hmxs_particulars1,
      particulars2,
      particulars3,
      particulars4]
  },
  3044: {
    title: '嘉华', banner: jiahuaBanner, descImgArr: [hmxs_particulars1,
      jhbw_particulars2,
      jhbw_particulars3,
      jhbw_particulars4]
  },
  3050: {
    title: '汉堡王', banner: hanbaoBanner, descImgArr: [hbw_particulars2]
  },
  3048: {
    title: '冷饮行业立减券', banner: lengyinBanner, descImgArr: [lyhy_particulars1,lyhy_particulars2]
  },
  3043: {
    title: '雪兰', banner: xuelanBanner, descImgArr: [xlnn_particulars2]
  },
  3053: {
    title: '美团外卖立减券', banner: meituanBanner, descImgArr: [mtwm_particulars2]
  },
  3041: {
    title: '微信通用立减金', banner: wxBanner, descImgArr: [wxlj_particulars2]
  }
}
const skuData = ref({})
const skuIdValue = ref()
const orderNo = ref('')
const disabledBtn = ref(false)

const btnStatueText = ref('立即领取')

onMounted(() => {
  skuIdValue.value = route.query.sku_id
  if (route.query.sku_id == 3053) {
    bgImage.value = orderTip5;
  }
  if (route.query.sku_id == 3047) {
    bgImage.value = orderTip6;
  }
  if (route.query.sku_id == 3049) {
    bgImage.value = orderTip7;
  }
  if (route.query.sku_id == 3034) {
    bgImage.value = orderTip8;
  }
  if (route.query.sku_id == 3044) {
    bgImage.value = orderTip9;
  }
  if (route.query.sku_id == 3045) {
    bgImage.value = orderTip10;
  }
  getSkuInfo()
  apiSkuStock()

  //  初始化判断商品是否已抢完
  if (storeData.value[skuIdValue] === 0) {
    showFailToast('该券已被抢完')
    disabledBtn.value = true
  }
})

const getSkuInfo = () => {
  skuInfo(skuIdValue.value).then((res) => {
    if (res.code !== 0) {
      showFailToast(res.msg);
    } else {
      skuData.value = res.data
      if (skuData.value.is_obtained === 1) {
        if (skuData.value.obtain_style === 'sale') {
          btnStatueText.value = '已购买'
        } else {
          btnStatueText.value = '已领过'
        }
      } else {
        if (skuData.value.obtain_style === 'sale') {
          btnStatueText.value = '立即购买'
        } else {
          btnStatueText.value = '立即领取'
        }
      }
    }
  }).catch((error) => {
    showFailToast(error.msg);
  })
}

const handleBocObtainChange = async () => {
  await bocObtain(skuIdValue.value).then((res) => {
    // 领取券成功，跳转到订单详情（订单状态）页面，带“订单号”
    if (res.code === 0) {
      orderNo.value = res.data.order_no
      if (res.data.order_no) {
        //判断领取方式（免费还是付费）
        if (skuData.value.obtain_style === 'free') {
          router.push({path: '/actResult', query: {order_no: res.data.order_no}})
          isOverlay.value = true
        } else {
          isOverlay.value = false
          payOrder(res.data.order_no)
        }
      } else {
        router.push({path: '/order'})
      }
    } else if (res.code === 400112) {
      showToast(res.msg)
      router.push({path: '/order'})
    } else if (res.code === 400117) {
      showToast(res.msg)
      router.push({path: '/actResult', query: {order_no: res.data.order_no}})
    } else {
      showToast(res.msg);
      isOverlay.value = false
    }
  }).catch((error) => {
    showFailToast(error.msg);
  })
}

const handleCopy = (value) => {
  navigator.clipboard.writeText(value).then(() => {
    showToast("复制成功")
  })
}

const handleGetBtnChange = () => {
  //判断是否领取过
  if (skuData.value.is_obtained === 1) {
    showToast("本月已领取！");
    router.push({path: '/order'})
    isOverlay.value = false
  } else {
    // isOverlay.value = true
    GetApiCheckObtain(skuIdValue.value)
  }
}

const GetApiCheckObtain = (value) => {
  checkObtain(value).then((res) => {
    if (res.code === 0) {
      isOverlay.value = true
    } else if (res.code === 400112) {
      showToast(res.msg)
      router.push({path: '/order'})
    } else if (res.code === 400117) {
      showToast(res.msg)
      router.push({path: '/actResult', query: {order_no: res.data.order_no}})
    } else {
      showFailToast(res.msg)
      isOverlay.value = false
    }
  })
}

const payOrder = (orderNo) => {
  payGetPayParams({order_no: orderNo})
      .then((res) => {
        if (res.code == 0) {
          const pay_params = res.data
          if (typeof WeixinJSBridge === "undefined") {
            if (document.addEventListener) {
              document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
            } else if (document.attachEvent) {
              document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady);
              document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);
            }
          } else {
            onBridgeReady(pay_params);
          }
        } else {
          showToast('微信支付调起失败！');
        }
      }).catch((err) => {
    console.log(err);
  })
}

const onBridgeReady = (params) => {
  const that = this;
  WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
        "appId": params.appId,  //公众号名称，由商户传入
        "timeStamp": params.timeStamp, //支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
        "nonceStr": params.nonceStr,  //支付签名随机串，不长于 32 位
        "package": params.package,//统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
        "signType": params.signType,  //签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
        "paySign": params.paySign, //支付签名
      },
      function (res) {
        if (res.err_msg === "get_brand_wcpay_request:ok") {
          showToast('支付成功！');
          paySuccess({order_no: orderNo.value});
          router.push({path: '/actResult', query: {order_no: orderNo.value}})
        } else {
          router.push({path: '/actResult', query: {order_no: orderNo.value}})
        }
      });
}

const apiSkuStock = () => {
  skuStock().then((res) => {
    if (res.code !== 0) {
      showFailToast(res.msg)
    } else {
      storeData.value = res.data
    }
  }).catch((error) => {
    showFailToast(error.msg)
  })
}
</script>

<style lang="scss" scoped>
.action_bar {
  height: 130px;

  .obtained_btn {
    background: #a6a6a6 !important;
  }
}

.content {
  width: 750px;
  position: relative;
  margin: 100px auto 130px;
  overflow: hidden;
  box-sizing: border-box;

  .result-img {
    width: 750px;
    height: 568px;
    line-height: 0;
    overflow: hidden;
  }
}

.title {
  background-color: #fff;
  margin-top: -8px;
  text-align: left;
  padding: 36px 0 36px 40px;
  line-height: 1.6em;
  color: #333333;
  box-sizing: border-box;
}

.act-desc {
  text-align: left;
  padding: 1em;
  line-height: 2em;
  background-color: #fff;
  margin-top: 1em;
}

.desc-title {
  line-height: 2em;
  color: #333333
}

.act-desc-box {
  border: .3em #EB6200 solid;
  border-radius: 1em;
  padding: 2em 1em;
  font-size: 1em;
  background-color: #FFFAF4;
  margin: -2.5em auto 0;

  .img {
    width: 100%;
    height: 100px;
  }
}


.cancel-btn {
  --van-button-default-color: #E2451B;
  --van-button-default-border-color: #E2451B;
  --van-button-default-font-size: 1.2em;
  width: 248px;
  height: 86px;
}

.confirm-btn {
  --van-button-default-color: #e8e8e8;
  width: 248px;
  height: 86px;
}


.wrapper {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 0 80px;
  width: 731px;
  height: 852px;
  //background: url("@/assets/image/order_tip_1.png") no-repeat;
  background-size: contain;
  box-sizing: border-box;

  .btn {
    margin-top: 686px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

}
</style>
